<?php

/**
 * +---------------------------------------------------------------
 * | Author: 北京永青宇创科技有限公司
 * | Date: 2020/03/12
 * | 版本: 6.0
 * +---------------------------------------------------------------
 * | CopyRight: 北京永青宇创科技有限公司 All rights reserved.
 * +---------------------------------------------------------------
 * | 版权声明：云豹不是一个自由软件，是云豹官方推出的商业源码。
 * | 严禁在未经许可的情况下拷贝、复制、传播、使用云豹的任意代码
 * | 如有违反，请立即删除，否则您将面临承担相应，法律责任的风险。
 * | 如果需要取得官方授权，请联系官方 https://www.gepardshop.com
 * +---------------------------------------------------------------
 */

namespace app\survey\controller\admin;;

use yunbao\modelhelp;
use app\common\controller\Backend;
use app\common\builder\FormBuilder;
use app\common\builder\SortBuilder;
use app\common\builder\ListBuilder;

class SurveyQuestion extends SurveyAdmin {
	protected $Model;

	public function initialize()
	{
		parent::initialize();
		$this->Model = model('surveyQuestion');
	}

	public function Index($page = 1, $r = 20)
	{
		$map     = [];
		$page_id = input('page_id', 0);
		if( ! empty($page_id))
			$map['page_id'] = $page_id;
		list($list, $pagehtml) = $this->Model->where($map)->pagedata($r);

		$builder = new ListBuilder();

		//处理标题和按钮
		$builder->setMetaTitle('问题管理');
		$builder->setSuggest('新版问题管理页面beta')
		        ->addTopButton('addnew', ['href' => url_admin('edit', $map)])
		        ->addTopButton('self', ['title' => '初始化问题选项', 'href' => url_admin('initQuestionItem', ['page_id' => $page_id]), 'model' => 'survey/surveyQuestion'])
		        ->addTopButton('self', ['title' => '批量排序', 'href' => url_admin('nest', $map)])
		        ->addTopButton('forbid', ['model' => 'survey/SurveyQuestion'])
		        ->addTopButton('recycle', ['model' => 'survey/SurveyQuestion'])
		        ->addSearchItem('status', 'select', '状态', '状态', ['1' => '正常', '0' => '已禁用', '-1' => '已删除'])
		        ->addSearchItem('create_time', 'dateranger', '发布时间', '发布时间')
		        ->addSearchItem('keyword', 'text', '关键字', '标题关键字');
		//处理字段
		$builder->addTableColumn('id', '编号', 'id');
		$builder->addTableColumn('title', '标题', 'text');
		$builder->addTableColumn('type', '类型id', 'text');
		$builder->addTableColumn('page_id', '页面id', 'foreign_id');
		$builder->addTableColumn('description', '简介', 'textarea');
		$builder->addTableColumn('num_score', '分数', 'integer');
		$builder->addTableColumn('status', '状态', 'toggle');
		$builder->addTableColumn('sort', '排序', 'integer');
		// $builder->addTableColumn('create_time', '创建时间', 'datetime');
		// $builder->addTableColumn('update_time', '更新时间', 'datetime');

		//渲染数据处理分页
		$builder->addTableColumn('right_button', '操作', 'btn')
		        ->setTableDataList($list)
		        ->setTableDataPage($pagehtml)
		        ->addRightButton('self', ['title' => '选项管理', 'href' => url_admin('survey/surveyItem/index', ['question_id' => '__data_id__'])])
		        ->addRightButton('edit', ['href' => url_admin('edit', ['id' => '__data_id__', 'page_id' => $page_id])])
		        ->addRightButton('delete', ['model' => 'survey/SurveyQuestion'])
		        ->setTemplate('layout/admin/list');

		return $builder->display();
	}

	public function initQuestionItem($page_id)
	{
		$map           = ['page_id' => $page_id];
		$question_list = $this->Model->where($map)->select();

		if(empty($page_id) || empty($question_list)) {
			$this->error('参数错误或者当前页面没有关联问题');
		}

		$insert_data = [];
		foreach($question_list as $item) {
			switch($item['type']) {
				case 'radio':
					$yes           = [
						'question_id' => $item['id'],
						'title'       => '是',
						'status'      => 1,
						'num_score'   => 1,
					];
					$no            = [
						'question_id' => $item['id'],
						'title'       => '否',
						'status'      => 1,
						'num_score'   => 0,
					];
					$insert_data[] = $yes;
					$insert_data[] = $no;
					break;
				case 'select':
					break;
				case 'checkbox':
					break;
				case 'textarea':
					break;
				case 'intval':
					break;
			}
		}
		$status = model('survey/surveyItem')->saveAll($insert_data);
		if($status) {
			$this->success('初始化成功');
		} else {
			$this->error('初始化失败');
		}
	}

	public function Edit($id = 0)
	{
		$map     = [];
		$page_id = input('page_id', 0);
		if( ! empty($page_id))
			$map['page_id'] = $page_id;

		if(request()->isPost()) {
			if($id != 0) {
				if($this->Model->allowField(true)->save(input(''), ['id' => $id])) {
					$this->success('操作成功', url_admin('surveyQuestion/Index'));
				} else {
					$this->error('操作失败');
				}
			} else {

				if($this->Model->allowField(true)->save(input(''))) {
					$this->success('操作成功', url_admin('surveyQuestion/Index'));
				} else {
					$this->error('操作失败');
				}
			}
		} else {
			$builder = new FormBuilder();

			if($id != 0) {
				$info = $this->Model->find($id);
			} else {
				$info = $map;
			}

			//处理标题
			$builder->setMetaTitle('问题编辑')
			        ->setPostUrl(url_admin('edit'));
			$page_info = model('surveyPage')->find($page_id);
			$page_map  = ['survey_id' => $page_info['survey_id']];
			//处理字段

			$builder->addFormItem('id', 'id', '编号');

			$builder->addFormItem('title', 'text', '标题');

			$builder->addFormItem('type', 'radio', '类型id', '', \yunbao\modelhelp::get_foreign_list('survey/surveyQuestionType', 'type'));

			$builder->addFormItem('page_id', 'radio', '页面id', '', \yunbao\modelhelp::get_foreign_list('survey/surveyPage', 'id', 'title', $page_map));

			$builder->addFormItem('description', 'textarea', '简介');

			$builder->addFormItem('num_score', 'integer', '分数');

			$builder->addFormItem('status', 'radio', '状态');

			$builder->addFormItem('sort', 'integer', '排序');

			$builder->addFormItem('create_time', 'datetime', '创建时间');

			$builder->addFormItem('update_time', 'datetime', '更新时间');

			$builder->setFormData($info)
			        ->setTemplate('layout/admin/form');

			return $builder->display();
		};
	}

	public function Del($id = 0)
	{
		$id = array_unique((array)input('id', 0));

		if(empty($id)) {
			$this->error(lang('_ERROR_DATA_SELECT_') . lang('_EXCLAMATION_'));
		}

		$map = ['id' => ['in', $id]];
		if($this->Model->where($map)->delete()) {

			$this->success('操作成功');
		} else {
			$this->error('操作失败');
		}
	}
}